package com.midongtech.cpd.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppUtils {

    private static final String TAG = "AppUtils";

    private static long lastClickTime;
    private static String sLastTopApp = "";
    private static String sLastTopAppActivity = "";

    /**
     * 获取App的名称
     */
    public static String getAppName(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //获取应用 信息
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            //获取albelRes
            int labelRes = applicationInfo.labelRes;
            //返回App的名称
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取安装列表app包名
     * @param context
     * @return
     */
    public final static synchronized String getAppList(Context context) {
        StringBuilder appList = new StringBuilder();
        if (context.getPackageManager() != null) {
            List<PackageInfo> packages = getInstalledPackages(context, 0);
            for (int i = 0; i < packages.size(); i++) {
                PackageInfo packageInfo = packages.get(i);
                //只有非系统应用才上报
                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    String appName = packageInfo.packageName;
                    appList.append(appName);
                    appList.append(",");
                }
            }
        }
        return appList.toString();
    }

    public static List<PackageInfo> getInstalledPackages(Context context, int flags) {
        final PackageManager pm = context.getPackageManager();
        try {
            return pm.getInstalledPackages(flags);
        } catch (Exception ignored) {
            //we don't care why it didn't succeed. We'll do it using an alternative way instead
        }
        //抛异常后,备选方案通过adb命令去获取已安装的应用列表(比较耗时,所以在异常捕获的前提下优先使用上面的系统api)
        Process process;
        List<PackageInfo> result = new ArrayList<>();
        BufferedReader bufferedReader = null;
        try {
            process = Runtime.getRuntime().exec("pm list packages");
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                final String packageName = line.substring(line.indexOf(':') + 1);
                final PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
                result.add(packageInfo);
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null)
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return result;
    }



    public static void startApp(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "startApp Exception:" + e.getMessage());
        }
    }



    /**
     * install app
     *
     * @param context
     * @param filePath
     * @return whether apk exist
     */

    public static boolean install(Context context, String filePath) {
        try {
            Intent myIntent = new Intent();
            myIntent.setAction("PACKAGE_INSTALL");
            context.sendBroadcast(myIntent);
            Intent i = new Intent(Intent.ACTION_VIEW);
            if (!filePath.endsWith(".apk"))
                filePath += ".apk";
            if (Build.VERSION.SDK_INT >= 24) {
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                File file = new File(filePath);
                if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
                    String packageName = context.getApplicationContext().getPackageName();
                    Uri contentUri = FileProvider.getUriForFile(context, packageName + ".cpdfileprovider", new File(filePath));
                    i.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    context.startActivity(i);
                    return true;
                }
            } else {
                File file = new File(filePath);
                if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
                    i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
                    // 让安装界面置顶
                    i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isApkValid(String apkPath, Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            if (info != null) {
                return true;
            } else {
                Log.e(TAG, "isApkValid Exception:" + false);
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "isApkValid Exception:" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


    public static boolean isAppInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            if (info == null) {
                return false;
            } else {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 判断当前设备中有没有“有权查看使用权限的应用”这个选项
     *
     * @param context
     * @return
     */
    public static boolean hasUsageOption(Context context) {
        PackageManager packageManager = context.getApplicationContext()
                .getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 判断调用该设备中“有权查看使用权限的应用”这个选项的APP有没有打开
     */
    public static boolean isSwitchOpen(Context context) {
        long ts = System.currentTimeMillis();
        UsageStatsManager usageStatsManager = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            usageStatsManager = (UsageStatsManager) context.getApplicationContext()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
        }
        if (usageStatsManager == null)
            return false;
        List<UsageStats> queryUsageStats = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            queryUsageStats = usageStatsManager.queryUsageStats(
                    UsageStatsManager.INTERVAL_BEST, 0, ts);
        }
        if (queryUsageStats != null && queryUsageStats.size() > 0)
            return true;
        else return false;
    }

    public static boolean isUsagePermissionAceess(Context context) {
        boolean isAccess = true;
        if (Build.VERSION.SDK_INT >= 21) {
            if (hasUsageOption(context)) {
                return isSwitchOpen(context);
            }
        }
       return isAccess;
    }


    public static String[] getTopAppInfo(Context context) {
        String[] info = new String[]{sLastTopApp, sLastTopAppActivity};
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> appTasks = activityManager.getRunningTasks(1);
            if (null != appTasks && !appTasks.isEmpty()) {
                info[0] = appTasks.get(0).topActivity.getPackageName();
                info[1] = appTasks.get(0).topActivity.getClassName();
                return info;
            }
        } else {
            long endTime = System.currentTimeMillis();
            long beginTime = endTime - 1 * 60 * 1000;
            UsageStatsManager manager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            String result = "";
            String resultActivity = "";
            UsageEvents.Event event = new UsageEvents.Event();
            UsageEvents usageEvents = manager.queryEvents(beginTime, endTime);
            while (usageEvents.hasNextEvent()) {
                usageEvents.getNextEvent(event);
                if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                    result = event.getPackageName();
                    resultActivity = event.getClassName();
                }
            }
            if (!TextUtils.isEmpty(result)) {
                sLastTopApp = result;
            }
            if (!TextUtils.isEmpty(resultActivity)) {
                sLastTopAppActivity = resultActivity;
            }
            info[0] = sLastTopApp;
            info[1] = sLastTopAppActivity;
            return info;
        }
        return info;
    }

}
